package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.*;
import com.itheima.ydd.dto.ArticleDto;
import com.itheima.ydd.dto.YddCateDto;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/index")
@Slf4j
public class SysIndexController {
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IYddAdvimgService iYddAdvimgService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IYddAdvposService iYddAdvposService;

    @Autowired
    private IYddCateService iYddCateService;

    @Autowired
    private  IYddTagService iYddTagService;

    @Autowired
    private IYddArticleService iYddArticleService;

    @Autowired
    private IYddUserService iYddUserService;

    @Autowired
    private IYddLinkService iYddLinkService;
    /**
     * 登录
     *
     * @param sysUser
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody SysUser sysUser) {
        log.info("登陆用户：{}", sysUser.toString());

        String loginName = sysUser.getLoginName();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getLoginName, loginName);
        SysUser one = sysUserService.getOne(wrapper);

        if (one == null) {
            return R.error("账号不存在");
        } else if (one.getStatus() == 0) {
            return R.error("账号已禁用");
        }

        String password = sysUser.getPassword();
        if (one.getPassword().equals(generatePassword(password))) {
            //把用户id 加密进token里

            // 生成token信息
            Map retMap = new HashMap();
            Map tokenMap = new HashMap<>();
            String roleId = one.getRoleId()
                    .replace("[", "")
                    .replace("]", "")
                    .replace("\"", "");

            tokenMap.put("userId", one.getId());
            tokenMap.put("roleId", roleId);

            String token = JwtUtils.getToken(tokenMap);
            retMap.put("token", token);
            return R.success("token", JwtUtils.getToken(tokenMap));
        }
        return R.error("密码错误");

    }
    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public void logout() {
        //删除用户信息
        UserHolder.remove();
    }


    /**
     * 获取系统配置
     *
     * @return
     */
    @GetMapping("/getConfig")
    public R systemConfig() {
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysConfig::getTabValue, "system");
        List<SysConfig> sysConfigs = sysConfigService.list(wrapper);

        HashMap<String, String> map = new HashMap<>();
        for (SysConfig sysConfig : sysConfigs) {
            map.put(sysConfig.getAttrKey(), sysConfig.getAttrValue());
        }

        return new R(map, "", 0);

    }

    /**
     * 主页统计信息
     *
     * @return
     */
    @GetMapping("/baseInfo")
    public ResultData baseInfo() {
        HashMap<String, Object> map = new HashMap<>();
        //获取管理账户数量
        int userCount = sysUserService.count();
        map.put("admin_num",userCount);
        //获取广告图数量
        int advimgCount = iYddAdvimgService.count();
        map.put("advimg_num",advimgCount);
        //获取广告位数量
        int advposCount = iYddAdvposService.count();
        map.put("advpos_num",advposCount);
        //获取标签数量
        int tagCount = iYddTagService.count();
        map.put("tag_num",tagCount);
        //分类总数
        int cateCount = iYddCateService.count();
        map.put("cate_num",cateCount);
        //文章总数
        int articleCount = iYddArticleService.count();
        map.put("article_num",articleCount);
        //获取所有分类文章数据
        List<YddCate> list = iYddCateService.list();
        List<YddCateDto> allCate = list.stream().map((cata) -> {
            YddCateDto yddCateDto = new YddCateDto();
            BeanUtils.copyProperties(cata, yddCateDto);
            LambdaQueryWrapper<YddArticle> lqw=new LambdaQueryWrapper<>();
            lqw.eq(YddArticle::getCateid,cata.getId());
            //对应分类文章的数量
            int count = iYddArticleService.count(lqw);
            yddCateDto.setNum(count);
            return yddCateDto;
        }).collect(Collectors.toList());
        map.put("all_cate",allCate);
        //获取注册的新用户
        Page<YddUser> userPage=new Page<>(1,7);
        LambdaQueryWrapper<YddUser> lqw=new LambdaQueryWrapper<>();
        lqw.orderByDesc(YddUser::getId);
        iYddUserService.page(userPage,lqw);
        map.put("new_user",userPage.getRecords());
        //获取热门文章数据
        Page<YddArticle> articlePage=new Page<>(1,7);
        LambdaQueryWrapper<YddArticle> lqw1=new LambdaQueryWrapper<>();
        lqw1.orderByDesc(YddArticle::getLovenum);
        iYddArticleService.page(articlePage,lqw1);
        map.put("hot_article",articlePage.getRecords());
        //获取用户数据
        HashMap<String,Object> user=new HashMap<>();
        int count = iYddUserService.count();
        int manCount = iYddUserService.count(lqw.eq(YddUser::getSex, 0));
        int womanCount =count-manCount;
        user.put("total",count);
        user.put("user_man",manCount);
        user.put("user_woman",womanCount);
        map.put("user",user);
        return ResultData.ok("",map);
    }

    /**
     * 获取用户资料
     *
     * @param
     * @return
     */
    @PostMapping("profile")
    public ResultData profile() {
        Map<String, Object> map = sysUserService.profile();
        return ResultData.ok("", map);
    }
    /**
     * 最新文章
     * @return
     */
    @GetMapping("/hot")
    public ResultData hot() {
        Map<String, Object> data = new HashMap<>();
        data.put("desc", "侧边最新文章");

        //获取最新文章
        Page<YddArticle> pageInfo = new Page<>(1, 10);
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(YddArticle::getLovenum);
        wrapper.orderByDesc(YddArticle::getId);
        wrapper.eq(YddArticle::getStatus, 2);

        iYddArticleService.page(pageInfo, wrapper);

        List<YddArticle> records = pageInfo.getRecords();

        List<ArticleDto> yddArticleDtos = records.stream().map(item -> {
            ArticleDto yddArticleDto = new ArticleDto();
            BeanUtils.copyProperties(item, yddArticleDto);
            LambdaQueryWrapper<YddCate> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(YddCate::getId, item.getCateid());
            YddCate yddCate = iYddCateService.getOne(wrapper1);
            if (yddCate != null) {
                yddArticleDto.setCatename(yddCate.getCatename());
            }
            return yddArticleDto;
        }).collect(Collectors.toList());

        data.put("list", yddArticleDtos);

        return ResultData.ok("",data);

    }

    /**
     * 首页侧边推荐文章
     *
     * @return
     */
    @GetMapping("/recommend")
    public ResultData recommend() {
        Map<String, Object> data = new HashMap<>();
        data.put("desc", "侧边推荐文章");

        //获取推荐文章
        Page<YddArticle> pageInfo = new Page<>(1, 10);
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(YddArticle::getId);
        wrapper.eq(YddArticle::getIshot, 1);
        wrapper.eq(YddArticle::getStatus, 2);
        List<YddArticle> yddArticles = iYddArticleService.list(wrapper);

        List<YddArticle> newArticles = new ArrayList<>();

        for (int i = 0; i < 6; i++) {
            newArticles.add(yddArticles.get(i));
        }

        List<ArticleDto> yddArticleDtos = newArticles.stream().map(item -> {
            ArticleDto yddArticleDto = new ArticleDto();
            BeanUtils.copyProperties(item, yddArticleDto);
            LambdaQueryWrapper<YddCate> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(YddCate::getId, item.getCateid());
            YddCate yddCate = iYddCateService.getOne(wrapper1);
            if (yddCate != null) {
                yddArticleDto.setCatename(yddCate.getCatename());
            }
            return yddArticleDto;
        }).collect(Collectors.toList());
        data.put("list", yddArticleDtos);
        return ResultData.ok("",data);
    }

    /**
     * 首页和全局数据
     *
     * @return
     */
    @GetMapping("/index")
    public R index() {

        //返回数据allCate,config,allTag,allLink,banner,sideBanner,showBanner
        Map<String, Object> data = new HashMap<>();

        //allCate
        List<YddCate> yddCates = iYddCateService.list();

        data.put("allCate", yddCates);

        //config
        Map<String, Object> config = new HashMap<>();
        //设置list
        List<Map<String, Object>> list = sysConfigService.getList();
        //设置alldata
        List<SysConfig> allData = sysConfigService.list();
        for (SysConfig sysConfig : allData) {
            if (sysConfig.getId() == 125) {
                List<Map<String, Object>> sysConfig125 = sysConfigService.get125ConfigValue();
                sysConfig.setConfigValue(sysConfig125.toString());
            }
        }
        config.put("list", list);
        config.put("allData", allData);

        data.put("config", config);

        //allTag
        List<YddTag> yddTags = iYddTagService.list();
        data.put("allTag", yddTags);

        //allLink
        List<YddLink> yddLinks = iYddLinkService.list();
        data.put("allLink", yddLinks);

        //banner
        LambdaQueryWrapper<YddAdvimg> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(YddAdvimg::getAdvimgpos, 15);
        List<YddAdvimg> yddAdvimgs = iYddAdvimgService.list(wrapper1);
        data.put("banner", yddAdvimgs);

        //sideBanner
        LambdaQueryWrapper<YddAdvimg> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(YddAdvimg::getAdvimgpos, 14);
        List<YddAdvimg> yddAdvimgsSide = iYddAdvimgService.list(wrapper2);
        data.put("sideBanner", yddAdvimgsSide);

        //showBanner
        LambdaQueryWrapper<YddAdvimg> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.ne(YddAdvimg::getAdvimgpos, 14);
        wrapper3.ne(YddAdvimg::getAdvimgpos, 15);

        List<YddAdvimg> yddAdvimgsShow = iYddAdvimgService.list(wrapper3);
        data.put("showBanner", yddAdvimgsShow);

        return R.success("",data);
    }

    /**
     * 获取文章详情
     * @param id
     * @return
     */
    @GetMapping("/show")
    public ResultData show(Integer id) {

        //data
        Map<String, Object> data = new HashMap<>();

        //获取前一篇文章title和id
        Integer prevId = id - 1;
        YddArticle prevArticle = iYddArticleService.getById(prevId);
        String prevArticleTitle = null;
        if(prevArticle != null){
            prevArticleTitle = prevArticle.getTitle();
        }
        Map<String, Object> prev = new HashMap<>();
        List<Map<String,Object>> list = new ArrayList<>();

        Map<String, Object> prevInfo = new HashMap<>();
        prevInfo.put("id",prevId);
        prevInfo.put("title",prevArticleTitle);
        list.add(prevInfo);
        data.put("prev",list);

        //获取后一篇文章title和id
        Integer nextId = id + 1;
        YddArticle nextArticle = iYddArticleService.getById(nextId);
        String nextArticleTitle = null;
        if(nextArticle != null){
            nextArticleTitle = nextArticle.getTitle();
        }
        Map<String, Object> next = new HashMap<>();
        prev.put("id",nextId);
        prev.put("title",nextArticleTitle);
        data.put("next",next);


        //获取推荐文章
        Page<YddArticle> pageInfo = new Page<>(0, 4);
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(YddArticle::getId);
        wrapper.eq(YddArticle::getIshot, 1);
        wrapper.eq(YddArticle::getStatus, 2);
        iYddArticleService.page(pageInfo, wrapper);
        List<YddArticle> records = pageInfo.getRecords();

        List<Map<String, Object>> recommend = records.stream().map(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", item.getId());
            map.put("title", item.getTitle());
            map.put("pic", item.getPic());
            map.put("cateid", item.getCateid());

            LambdaQueryWrapper<YddCate> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(YddCate::getId, item.getCateid());
            YddCate yddCate = iYddCateService.getOne(wrapper1);
            if (yddCate != null) {
                map.put("catename", yddCate.getCatename());
            }
            return map;
        }).collect(Collectors.toList());
        data.put("recommend", recommend);

        //获取info
        YddArticle article = iYddArticleService.getById(id);

        //返回ArticleDto
        ArticleDto yddArticleDto = new ArticleDto();
        BeanUtils.copyProperties(article, yddArticleDto);

        //获取cate name
        LambdaQueryWrapper<YddCate> wrapper1 = new LambdaQueryWrapper<>();
        if(article.getCateid() != null){
            wrapper1.eq(YddCate::getId, article.getCateid());
            YddCate yddCate = iYddCateService.getOne(wrapper1);
            yddArticleDto.setCatename(yddCate.getCatename());
        }
        data.put("info", yddArticleDto);

        return ResultData.ok("",data);
    }
    /**
     * 热门置顶文章数据
     * @param page1
     * @param limit
     * @return
     */
    @GetMapping("/new")
    public ResultData newPage(@RequestParam("page")String page1, String limit){
        int page = Integer.parseInt(page1);
        int pageSize = Integer.parseInt(limit);
        //分页参数 和条件查询top和hot
        Page<YddArticle> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<YddArticle> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YddArticle::getIstop,1);
        lqw.eq(YddArticle::getIshot,1);
        iYddArticleService.page(pageInfo,lqw);
        //数据
        List<YddArticle> articleList = pageInfo.getRecords();

        List<ArticleDto> list = new ArrayList<>();
        for (YddArticle article : articleList) {
            ArticleDto articleDto = new ArticleDto();
            BeanUtils.copyProperties(article,articleDto);
            articleDto.setCatename(iYddCateService.getById(article.getCateid()).getCatename());
            list.add(articleDto);
        }
        //总条数
        long count = articleList.size();
        //总页数
        long totalPage = count % pageSize == 0 ? count/pageSize : count/pageSize + 1;
        //封装到MyPage
        MyPage myPage = new MyPage(count,totalPage,(long)pageSize,(long)page,list);
        //查询一周更新文章数量
        long time=System.currentTimeMillis();
        long weekTime = time - 3600*24*7*1000;
        long dayTime = time - 3600*24*1000;

        LambdaQueryWrapper<YddArticle> lqw2 = new LambdaQueryWrapper<>();
        lqw2.between(YddArticle::getCreateDate,weekTime,time);
        int numWeek = iYddArticleService.count(lqw2);
        //查询一天更新文章数
        LambdaQueryWrapper<YddArticle> lqw3 = new LambdaQueryWrapper<>();
        lqw3.between(YddArticle::getCreateDate,dayTime,time);
        int numDay = iYddArticleService.count(lqw3);
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("desc","首页大列表");
        hashMap.put("num_day",numDay);
        hashMap.put("num_Week",numWeek);
        hashMap.put("list",myPage);
        return ResultData.ok("",hashMap);
    }

    /**
     * 文章列表数据
     * @param page1
     * @param limit
     * @param cateid1
     * @return
     */
    @GetMapping("/list")
    public ResultData list(@RequestParam("page")String page1,String limit,@RequestParam("cateid")String cateid1){
        int page = Integer.parseInt(page1);
        int pageSize = Integer.parseInt(limit);
        int cateid = Integer.parseInt(cateid1);

        //cateid 分类查
        Page<YddArticle> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<YddArticle> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YddArticle::getCateid,cateid);
        iYddArticleService.page(pageInfo,lqw);
        //数据
        List<YddArticle> articleList = pageInfo.getRecords();

        List<ArticleDto> list = new ArrayList<>();
        for (YddArticle article : articleList) {
            ArticleDto articleDto = new ArticleDto();
            BeanUtils.copyProperties(article,articleDto);
            articleDto.setCatename(iYddCateService.getById(article.getCateid()).getCatename());
            list.add(articleDto);
        }
        //总条数
        long count = articleList.size();
        //总页数
        long totalPage = count % pageSize == 0 ? count/pageSize : count/pageSize + 1;
        //封装到MyPage
        MyPage myPage = new MyPage(count,totalPage,(long)pageSize,(long)page,list);

        return ResultData.ok("",myPage);
    }

    /**
     * 注册
     * @param yddUser
     * @return
     */
    @PostMapping("/reg")
    public ResultData register(@RequestBody YddUser yddUser){
        //先查手机号
        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUser::getMobile, yddUser.getMobile());
        int count = iYddUserService.count(wrapper);
        if (count > 0) {
            throw new BusinessException("该手机号已存在!");
        }
        //加密
        String password = DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes());

        yddUser.setPassword(password);

        yddUser.setUsername(yddUser.getMobile());
        //保存
        iYddUserService.save(yddUser);

        //生成token
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("userId", yddUser.getId());
        String token = JwtUtils.getToken(tokenMap);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);

        return ResultData.ok("注册成功",map);
    }

    /**
     * md5加密
     *
     * @param password 密码
     */
    private String generatePassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }
}
